<?php
/*
 +----------------------------------------------------------------------
 + Title        : ExcelController 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2023/8/12 8:12
 + Last-time    : 2023/8/12 8:12+ chen2
 + Desc         : ExcelController
 +----------------------------------------------------------------------
*/


namespace app\api\controller\common;

use app\api\controller\ApiBaseController;
use randy\tools\ali\AliOss;
use randy\tools\units\ExtendExcel;
use randy\tools\units\Snowflake;
use think\App;
use think\facade\Filesystem;

class ExcelController extends ApiBaseController
{
    protected $middleware = [];
    public function initialize(){
    }

    public function parse()
    {
        $file = request()->file('file');
        $res['file']['name'] =$file->getOriginalName();
        $res['file']['mimeType'] =$file->getMime();
        $fieldArr = $this->getParams();
        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            $info = Filesystem::putFile('upload', $file);
            $config = Filesystem::getDiskConfig('local');

            if ($info) {
                // 成功上传后 获取上传信息
                $info = $config['root'] . '/' . $info;
                //将\ 转换成 /
                $filePath = str_replace('\\', '/', $info);
                $photo = config('app.alioss.file_path') . "/upload" . '/' . Snowflake::get() . '.' . $file->extension();
                try {
                    $oss = new AliOss();
                    $url = $oss->uploadOss($info, $photo);
                    $res['file']['url'] = $url;
                    $res['file']['uid'] = (string)snow_id();
                    $res['file']['path'] = $photo;
                    $res['items'] = ExtendExcel::import($fieldArr);
                    return $this->returnSuccess($res);
                } catch (\Exception $e) {
                    @unlink($filePath);
                    throw $e;
                }
            } else {
                error_abort('文件上传失败');
            }
        } else {
            error_abort('上传文件不存在');
        }
    }
}